import {
	Button,
	Collapse,
	Form,
	Row,
	Col,
	Input,
	Select,
	Upload,
	TreeSelect,
	Cascader,
	message,
	Tag,
	Space,
	DatePicker,
	Modal,
} from 'antd'
import React, {useState, useEffect, memo, useRef} from 'react'
import {history, connect} from 'umi'
import moment from 'moment'
import styles from './index.less'
import CustomTable from '@/components/Table'
import SearchForm from '@/components/SearchForm'
import {translateDataToTree} from '@/utils/common/index'
import {
	addApply,
	editApply,
	viewApply,
	getInitiationAccessList,
	getPageInitiationAccessList,
	dictByCode,
	getProcessPropertys,
	contractProcessAdd,
	contractRelaunchFlow,
	getNodePropertys,
	getAmcpurchasesupplier,
	contractAuditFlow,
	applySaveTemporary,
} from '@/service/purchase/apply'
import {getIsProcessOpen} from '@/service/purchase/initiation'
import {getCompany} from '@/service/system/company'
import {
	getAllCitysPermission,
	getOnlydept,
	processRecordSave,
} from '@/service/common/index'
import {getAllSupplierAccessList} from '@/service/supplier/supplierAccess'
// 获取供应商准入列表
import {getBusinessCode} from '@/service/purchase/common'
import {contractList} from '@/service/purchase/contract'
import {getAllList, getDetailPlanList} from '@/service/purchase/plan'
import {twoDecimalPattern} from '@/utils/common/validator'
import {uploadMoreProps, getPublicDownloadUrl} from '@/service/common/upload'
import {auditStatus} from '../../dict'

import 'moment/locale/zh-cn'
import RecommendList from '../components/RecommendList'
import Examine from '../components/Examine'
import OperationRecord from '@/components/OperationRecord'

const {Panel} = Collapse
const {TextArea} = Input

interface CityOption {
	value: string | number
	label: string
	children?: CityOption[]
}

type TreeItem = {
	id: string
	parentId: number
	name: string
	children?: Array<TreeItem>
}[]

const formItemLayout = {
	labelCol: {flex: '110px'},
	wrapperCol: {flex: '1'},
}

const add = memo(
	(props: {
		global: {currentRoute: any}
		dispatch: any
		user: {orgId: string | number; userName: string; permissionID: any}
		location: any
	}) => {
		const {dispatch} = props
		const {currentRoute} = props.global
		const {orgId, userName, permissionID} = props?.user || {}
		const [applyId, setApplyId] = useState<string>()
		const [type, setType] = useState<string>()
		const [processOpen, setProcessOpen] = useState<number>(0)
		// 组织
		const [orgList, setOrgList] = useState<TreeItem>([])
		// 城市
		const [citysList, setCitysList] = useState<CityOption[]>([])
		// 部门
		const [deptList, setDeptList] = useState<TreeItem>([])
		const [otherParams, setOtherParams] = useState<any>()
		// 项目立项详情列表
		const [initiationView, setInitiationView] = useState<any[]>([])
		// 供应商列表
		const [supplierList, setSupplierList] = useState([])
		// 供应商详情列表
		const [supplierView, setSupplierView] = useState<any[]>([])
		// 合同列表
		const [contractView, setContractView] = useState([])
		// 计划列表
		const [planView, setPlanView] = useState<any[]>([])
		const [estimatedAmount, setEstimatedAmount] = useState<any>(0)
		// 采购类目
		const [requisitionTypeList, setRequisitionTypeList] = useState<any[]>(
			[],
		)
		const [fileList, setFileList] = useState<any>([])
		const [form] = Form.useForm()
		const [initiationForm] = Form.useForm()
		const [supplierForm] = Form.useForm()
		const [params, setParams] = useState({
			current: 1,
			size: 10,
		})
		const [seachFormData, setSeachFormData] = useState({})
		const [formDataInit, setFormDataInit] = useState<any[]>([])
		const [pageInitiationList, setPageInitiationList] = useState<any[]>([])
		const [total, setTotal] = useState(0)
		const [checkData, setCheckData] = useState<any>([])
		const examineRef = useRef<any>(null)
		// 是否显示推荐供应商
		const [recommend, setRecommend] = useState<string>()
		// 是否推荐供应商
		const [recommendStatus, setRecommendStatus] = useState(2)
		const [recommendData, setRecommendData] = useState<any[]>([])
		// 流程id
		const [instanceId, setInstanceId] = useState<string>()
		// 节点id
		const [activityId, setActivityId] = useState<string>()
		// 审核状态
		const [auditStatusType, setAuditStatusType] = useState<string>('0')
		// 弹窗
		const [isOpen, setIsOpen] = useState<boolean>(false)
		const [recommendSupplier, setRecommendSupplier] = useState<any>([])
		const [newApplyTime, setNewApplyTime] = useState('')
		const [selectOrgId, setSelectOrgId] = useState('')
		const [passStatus, setPassStatus] = useState<string>('')

		// 初始化-流程是否激活
		const getIsProcessOpenFun = () => {
			getIsProcessOpen({businessType: 2})
				.then((res: any) => {
					if (res?.success) {
						setProcessOpen(() => res?.data)
					}
				})
				.catch((err: any) => {
					message.error(err)
				})
		}

		// 初始化分页
		useEffect(() => {
			const param = {
				current: 1,
				size: 10,
			}
			setParams(() => param)
		}, [seachFormData])

		const goback = () => {
			dispatch({
				type: 'global/deleteTabs',
				payload: currentRoute,
			})
			history.push({
				pathname: '/purchase/apply',
			})
		}

		// 搜索
		const onFinish = (values: any) => {
			setSeachFormData(values)
		}

		// 搜索重置
		const onReset = () => {
			setSeachFormData({})
		}
		useEffect(() => {
			const formItems: any[] = [
				{
					type: 'group',
					key: 'group1',
					groupItems: [
						{
							type: 'input',
							label: '立项编号',
							name: 'projectNo',
							key: 'projectNo',
						},
						{
							type: 'input',
							label: '项目名称',
							name: 'projectName',
							key: 'projectName',
						},
						{
							type: 'input',
							label: '项目负责人',
							name: 'principalName',
							key: 'principalName',
						},
					],
				},
			]
			setFormDataInit(formItems)
		}, [])

		/** 初始化-是否推荐供应商 */
		const getProcessPropertysFun = () => {
			getProcessPropertys({businessType: 2})
				.then((res: any) => {
					if (res?.success) {
						setRecommend(res?.data?.startnodeRecommendSupplier)
					}
				})
				.catch((err: any) => {
					message.error(err)
				})
		}
		// 获取推荐供应商列表
		useEffect(() => {
			const {id} = props.location.query
			if (id && type) {
				getAmcpurchasesupplier({requisitionId: id})
					.then((res: any) => {
						if (res?.success) {
							const newData = res?.data?.map(
								(item: {id: any}) => ({
									...item,
									key: item?.id,
								}),
							)
							setRecommendData(newData)
							if (
								res?.data?.length === 0 &&
								(type === 'view' || type === 'process')
							) {
								setRecommendStatus(2)
							} else {
								setRecommendStatus(1)
							}
						}
					})
					.catch((err) => {
						setRecommendData([])
						message.error(err)
					})
			}
		}, [type])

		useEffect(() => {
			if (type === 'process' && instanceId) {
				getNodePropertys({businessType: 2, instanceId})
					.then((res: any) => {
						if (res?.success) {
							setActivityId(res?.data?.activityId)
						}
					})
					.catch((err: any) => {
						message.error(err)
					})
			}
		}, [type, instanceId])

		const initiationColumns = [
			{
				title: '立项编号',
				dataIndex: 'projectNo',
				align: 'center',
				width: 300,
				render: (text: any, record: any) => (
					<>
						<Button
							type="link"
							size="small"
							onClick={() => {
								const {id} = props.location.query
								history.push({
									pathname: '/purchase/initiation/view',
									query: {
										id: record?.id,
										goPath: props.location.pathname,
										pathParams: id,
									},
								})
							}}>
							{text}
						</Button>
					</>
				),
			},
			{
				title: '项目名称',
				dataIndex: 'projectName',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '审核状态',
				dataIndex: 'auditStatus',
				align: 'center',
				width: 150,
				render: (text: number, record: any) => {
					if (!text) {
						return '--'
					}
					return (
						<>
							{auditStatus?.map(
								(item: {key: number; label: string}) => {
									if (item?.key === Number(text)) {
										return (
											<Tag
												color="processing"
												key={record?.id}>
												{item?.label}
											</Tag>
										)
									}
									return ''
								},
							)}
						</>
					)
				},
			},
			{
				title: '项目负责人',
				dataIndex: 'principalName',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '项目开始日期',
				dataIndex: 'startTime',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '项目结束日期',
				dataIndex: 'finishTime',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '费用类型',
				dataIndex: 'costsNames',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '项目预算金额',
				dataIndex: 'budget',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '剩余预算金额',
				dataIndex: 'budgetSurplus',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},

			{
				title: '城市',
				dataIndex: 'applyCityname',
				editable: true,
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '立项申请人',
				dataIndex: 'applyUsername',
				editable: true,
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '申请日期',
				dataIndex: 'applyTime',
				editable: true,
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
		]
		const initiationSelectColumns = [
			{
				title: '立项编号',
				dataIndex: 'projectNo',
				align: 'center',
				width: 300,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '项目名称',
				dataIndex: 'projectName',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '项目负责人',
				dataIndex: 'principalName',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '项目开始日期',
				dataIndex: 'startTime',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '项目结束日期',
				dataIndex: 'finishTime',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '费用类型',
				dataIndex: 'costsNames',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '申请日期',
				dataIndex: 'applyTime',
				editable: true,
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
		]
		const supplierColumns = [
			{
				title: '供应商编号',
				dataIndex: 'supplierCode',
				editable: true,
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '供应商名称',
				dataIndex: 'supplierName',
				editable: true,
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '供应商联系人&联系方式',
				dataIndex: 'contactPhone',
				editable: true,
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			// {
			// 	title: '供应商联系方式',
			// 	dataIndex: 'contactPhone',
			// 	editable: true,
			// 	align: 'center',
			// 	width: 200,
			// 	render: (text: string) => <span>{text || '--'}</span>,
			// },
		]
		const contractColumns = [
			{
				title: '合同编号',
				dataIndex: 'contractNo',
				width: 300,
				align: 'center',
				render: (text: any, record: any) => (
					<>
						{text ? (
							<Button
								type="link"
								size="small"
								onClick={() => {
									const {id} = props.location.query
									history.push({
										pathname: '/purchase/contract/view',
										query: {
											id: record?.id,
											goPath: props.location.pathname,
											pathParams: id,
										},
									})
								}}>
								{text}
							</Button>
						) : (
							'--'
						)}
					</>
				),
			},
			{
				title: '合同签订日期',
				dataIndex: 'applyTime',
				width: 180,
				align: 'center',
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '采购类目',
				dataIndex: 'requisitionName',
				width: 140,
				align: 'center',
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '需求组织',
				dataIndex: 'requisitionOrgname',
				width: 140,
				align: 'center',
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '合同名称',
				dataIndex: 'contractName',
				width: 140,
				align: 'center',
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '采购方',
				dataIndex: 'purchaserName',
				width: 140,
				align: 'center',
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '供应商',
				dataIndex: 'supplierName',
				width: 140,
				align: 'center',
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '合同金额（元）',
				dataIndex: 'amount',
				width: 140,
				align: 'center',
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '合同期限',
				dataIndex: 'contactPhone',
				width: 240,
				align: 'center',
				render: (text: string, record: any) => (
					<>
						<span>
							{moment(record.startTime).format('YYYY-MM-DD') ||
								'--'}
						</span>
						至
						<span>
							{moment(record.finishTime).format('YYYY-MM-DD') ||
								'--'}
						</span>
					</>
				),
			},
		]
		const planColumns = [
			{
				title: '采购计划申请单编号',
				dataIndex: 'planNo',
				width: 200,
				align: 'center',
				render: (text: any, record: any) => (
					<>
						{text ? (
							<Button
								type="link"
								size="small"
								onClick={() => {
									const {id} = props.location.query
									history.push({
										pathname: '/purchase/plan/view',
										query: {
											id: record?.id,
											goPath: props.location.pathname,
											pathParams: id,
										},
									})
								}}>
								{text}
							</Button>
						) : (
							'--'
						)}
					</>
				),
			},
			{
				title: '采购类目',
				dataIndex: 'requisitionName',
				width: 140,
				align: 'center',
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '费用承担公司',
				dataIndex: 'payCityname',
				width: 140,
				align: 'center',
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '费用承担部门',
				dataIndex: 'payDeptname',
				width: 140,
				align: 'center',
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '收货联系人',
				dataIndex: 'consignee',
				width: 140,
				align: 'center',
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '收货电话',
				dataIndex: 'consigneeTel',
				width: 140,
				align: 'center',
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '收货地址',
				dataIndex: 'consigneeAddress',
				width: 200,
				align: 'center',
				render: (text: string) => <span>{text || '--'}</span>,
			},
		]

		// 初始化-采购类目
		const onDictByCodeFun = () => {
			dictByCode('purchase_requisition_type')
				.then((res: any) => {
					if (res?.success) {
						setRequisitionTypeList(() => res?.data)
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}

		// 初始化-项目编码
		const onCodeFun = () => {
			getBusinessCode({businessType: 2})
				.then((res: any) => {
					if (res?.success) {
						form.setFieldsValue({requisitionNo: res?.data})
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}

		// 初始化-城市
		// const getCitysFun = () => {
		// 	getAllCitys().then((res: any) => {
		// 		if (res?.success) {
		// 			setCitysList(() => res?.data)
		// 		}
		// 	})
		// }
		// 初始化-城市
		const getCitysFun = () => {
			const d = {
				permission: permissionID,
				orgId: selectOrgId,
			}
			getAllCitysPermission(d).then((res: any) => {
				if (res?.data) {
					setCitysList(() => res.data)
				}
			})
		}
		useEffect(() => {
			if (selectOrgId && permissionID) {
				getCitysFun()
			}
		}, [selectOrgId, permissionID])

		// 初始化-需求组织数据
		const getOrgFun = () => {
			getCompany({merchantId: orgId}).then((res: any) => {
				if (res?.success) {
					const list = translateDataToTree(res.data)
					setOrgList(() => list as any)
				}
			})
		}

		// 初始化-申请部门
		const getOnlydeptFun = () => {
			getOnlydept({merchantId: orgId}).then((res: any) => {
				if (res?.success) {
					const list = translateDataToTree(res.data)
					setDeptList(list as unknown as TreeItem)
				}
			})
		}

		useEffect(() => {
			if (orgId) {
				getOrgFun()
				getOnlydeptFun()
			}
		}, [orgId])

		// 供应商变化
		const onAccessListChange = (value: string, option: any) => {
			const data = {
				...otherParams,
				supplierId: option?.id,
				supplierNo: option?.supplierCode,
				supplierName: option?.supplierName,
				supplierPerson: option?.contactPhone,
				supplierNumber: option?.contactPhone,
			}
			setOtherParams(() => data)
			setSupplierView([option])
		}
		// 获取立项信息分页列表
		const getPageInitiationList = () => {
			getPageInitiationAccessList({...params, ...seachFormData})
				.then((res: any) => {
					if (res?.success) {
						setPageInitiationList(() => res?.data?.records)
						setTotal(() => res?.data?.total)
					}
				})
				.catch((err: any) => {
					message.error(err)
				})
		}
		useEffect(() => {
			if (orgId && isOpen) {
				getPageInitiationList()
			}
		}, [params, isOpen])
		// 获取立项信息列表
		const getInitiationList = (applycostId?: any) => {
			getInitiationAccessList({id: applycostId})
				.then((res: any) => {
					if (res?.success) {
						if (applycostId) {
							const row =
								res?.data?.filter(
									(item: any) => item?.id === applycostId,
								) || []
							setInitiationView(() => row)
							setCheckData(() => row)
						}
					}
				})
				.catch((err: any) => {
					message.error(err)
				})
		}

		// 获取采购合同list
		const getContractList = (requisitionNo?: any) => {
			contractList({requisitionNo})
				.then((res: any) => {
					if (res?.success) {
						setContractView(() => res?.data)
					}
				})
				.catch((err: any) => {
					message.error(err)
				})
		}

		// 获取采购计划list
		const getPlanList = (requisitionNo?: any) => {
			getAllList({requisitionNo})
				.then((res: any) => {
					if (res?.success) {
						setPlanView(() => res?.data)
					}
				})
				.catch((err: any) => {
					message.error(err)
				})
		}

		// 获取详情采购计划list
		const getDetailPlanTableList = (requisitionNo?: any) => {
			getDetailPlanList({requisitionNo})
				.then((res: any) => {
					if (res?.success) {
						setPlanView(() => res?.data)
					}
				})
				.catch((err: any) => {
					message.error(err)
				})
		}

		// 初始化-附件列表
		const getFileList = (ids: any) => {
			getPublicDownloadUrl(ids).then((res: any) => {
				if (res?.success) {
					const list = res?.data.map((item: any) => ({
						name: item?.filename,
						status: 'done',
						url: item?.url,
						response: {
							data: {
								id: item?.id,
							},
						},
					}))
					setFileList(() => [...list])
				}
			})
		}

		// 初始化-详情数据
		const getView = (id: string, viewType: string) => {
			viewApply(id).then((res: any) => {
				if (res?.success) {
					setSelectOrgId(res?.data?.requisitionOrgid)
					setNewApplyTime(res?.data?.applyTime)
					delete res?.data?.applyTime
					if (res?.data?.auditStatus === '3') {
						setRecommendStatus(1)
					} else if (res?.data?.recommendSupplier) {
						setRecommendSupplier([res?.data?.recommendSupplier])
						setRecommendStatus(1)
					}

					setInstanceId(res?.data?.instanceId)
					setAuditStatusType(res?.data?.auditStatus)
					form.setFieldsValue({
						...res?.data,
						city: [
							res?.data?.requisitionProvinceid,
							res?.data?.requisitionCityid,
						],
					})
					setEstimatedAmount(() => res?.data?.estimatedAmount)
					const data = {
						...otherParams,
						requisitionName: res.data.requisitionName,
						requisitionOrgname: res.data.requisitionOrgname,
						supplierName: res.data.supplierName,
						supplierNo: res.data.supplierNo,
						applicantId: res.data.applicantId,
						supplierId: res.data.supplierId,
						requisitionDeptname: res.data.requisitionDeptname,
						requisitionCityname: res.data.requisitionCityname,
						requisitionProvincename:
							res.data.requisitionProvincename,
						requisitionProvinceid: res.data.requisitionProvinceid,
						requisitionCityid: res.data.requisitionCityid,
						cityId: res.data.cityId,
						applycostId: res.data.applycostId,
						applycostName: res.data.applycostName,
					}
					setOtherParams(() => data)
					form.setFieldsValue({
						attachmentList: [],
					})
					initiationForm.setFieldsValue({
						projectName: res.data.applycostName
							? res.data.applycostName
							: null,
					})
					getInitiationList(res?.data?.applycostId)
					let sourceType = ''
					if (res?.data?.sourceType === 0) {
						sourceType = '例外采购'
					} else if (res?.data?.sourceType === 1) {
						sourceType = '比价会签'
					}
					supplierForm.setFieldsValue({
						supplierNo: res?.data?.supplierNo,
						sourceType,
					})
					setSupplierView([
						{
							supplierCode: res.data.supplierNo,
							supplierName: res.data.supplierName,
							contactPhone: res.data.supplierPerson,
						},
					])

					getContractList(res?.data?.requisitionNo)
					if (viewType === 'view') {
						getDetailPlanTableList(res?.data?.requisitionNo)
					} else {
						getPlanList(res?.data?.requisitionNo)
					}

					if (res?.data?.attachmentList.length) {
						getFileList(res?.data?.attachmentList)
					}
				}
			})
		}

		const getAccessList = () => {
			getAllSupplierAccessList()
				.then((res: any) => {
					if (res?.success) {
						setSupplierList(() => res?.data)
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}

		// 需求组织变化
		const onRequisitionOrgChange = (value: string, option: any) => {
			setSelectOrgId(value)
			setOtherParams({...otherParams, requisitionOrgname: option[0]})
			form.setFieldsValue({
				city: undefined,
			})
		}
		useEffect(() => {
			if (type === 'add' || type === 'edit') {
				getProcessPropertysFun()
			} else {
				setRecommend('1')
			}
		}, [type])

		// 根据路由判断当前页面状态
		useEffect(() => {
			const {id} = props.location.query
			if (id) {
				setApplyId(() => id)
			}
			getAccessList()
			onDictByCodeFun()
			getIsProcessOpenFun()
			const hrefs = window.location.href
			if (hrefs.includes('view')) {
				setType(() => 'view')
				getView(id, 'view')
			} else if (hrefs.includes('add')) {
				onCodeFun()
				setType(() => 'add')
				getInitiationList()
				form.setFieldsValue({
					applicantName: userName,
					applyTime: moment(moment().format('YYYY-MM-DD HH:mm:ss')),
				})
				setOtherParams({
					...otherParams,
					applicantId: orgId,
				})
			} else if (hrefs.includes('edit')) {
				setType(() => 'edit')
				getView(id, 'edit')
			} else {
				setType(() => 'process')
				getView(id, 'process')
			}
		}, [])

		useEffect(() => {
			if (newApplyTime) {
				if (
					auditStatusType &&
					auditStatusType === '4' &&
					window.location.href.includes('edit') &&
					processOpen === 1
				) {
					form.setFieldsValue({
						applyTime: moment(
							moment().format('YYYY-MM-DD HH:mm:ss'),
						),
					})
				} else {
					form.setFieldsValue({
						applyTime: moment(newApplyTime),
					})
				}
			}
		}, [auditStatusType, processOpen, newApplyTime])
		const customizeHeader = (value: string) => (
			<div>
				<div className={styles.tip} />
				{value}
			</div>
		)

		const submit = async (btnType: string) => {
			const formData = await form.validateFields()
			const initiationFormData = await initiationForm.validateFields()
			const supplierFormData = await supplierForm.validateFields()
			const attachmentList = formData?.attachmentList?.fileList?.map(
				(item: any) => Number(item?.response?.data?.id),
			)
			const applyTime = moment(formData.applyTime).format(
				'YYYY-MM-DD HH:mm:ss',
			)
			// if (
			// 	Number(formData?.estimatedAmount) >
			// 	initiationView[0]?.budgetSurplus
			// ) {
			// 	message.error('采购预估金额不能大于剩余预算金额')
			// 	return false
			// }
			let request
			const queryData = {
				...formData,
				...otherParams,
				...initiationFormData,
				...supplierFormData,
				applyTime,
				attachmentList: attachmentList || [],
			}
			if (recommendData?.length) {
				const newData = recommendData?.map((item) => {
					// eslint-disable-next-line @typescript-eslint/no-unused-vars
					const {key, ...info} = item
					return info
				})
				queryData.supplierList = newData
			}
			if (recommendStatus === 1) {
				queryData.isRecommendSupplier = 1
			}
			if (btnType === 'submit') {
				if (auditStatusType === '9' || !applyId) {
					const newQueryData = {
						...queryData,
					}
					if (applyId) {
						newQueryData.id = applyId
					}
					if (processOpen === 1) {
						request = contractProcessAdd(newQueryData)
					} else {
						request = addApply(newQueryData)
					}
				} else if (processOpen === 1 && auditStatusType === '4') {
					request = contractRelaunchFlow(applyId, queryData)
				} else {
					request = editApply(applyId, queryData)
				}
			}
			if (btnType === 'save') {
				const newQueryData = {
					...queryData,
				}
				if (applyId) {
					newQueryData.id = applyId
				}
				request = applySaveTemporary(newQueryData)
			}
			request
				?.then((res) => {
					if (res.success) {
						message.success(res.msg)
						goback()
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}

		// 城市变化
		const onCitysChange = (value: any, selectedOptions: any) => {
			if (value) {
				setOtherParams({
					...otherParams,
					requisitionProvincename: selectedOptions[0].name,
					requisitionProvinceid: selectedOptions[0].id,
					cityId: selectedOptions[1].id,
					requisitionCityid: selectedOptions[1].id,
					requisitionCityname: selectedOptions[1].name,
				})
			}
		}

		// 申请部门变化
		const onApplyDeptChange = (value: string, option: any) => {
			setOtherParams({...otherParams, requisitionDeptname: option[0]})
		}

		// 采购类目变化
		const onRequisitionTypeChange = (value: string, option: any) => {
			setOtherParams({...otherParams, requisitionName: option[0]})
		}

		// 立项编号变化
		const onApplycostIdChange = () => {
			if (checkData.length > 0) {
				setOtherParams({
					...otherParams,
					applycostId: checkData[0]?.id,
				})
				initiationForm.setFieldsValue({
					projectName: checkData[0]?.projectName,
				})
				setInitiationView(checkData)
			} else {
				setOtherParams({
					...otherParams,
					applycostId: null,
				})
				setInitiationView([])
				initiationForm.setFieldsValue({projectName: null})
			}
			setSeachFormData({})
			setIsOpen(false)
		}

		/** 审核 */
		const onCompleteTask = async (pass: string) => {
			if (examineRef?.current) {
				const examineData = await examineRef?.current?.getData()
				if (examineData) {
					if (examineData?.url) {
						// eslint-disable-next-line no-shadow
						const {supplierList, ...info} = examineData
						const flowParams: any = {
							message: JSON.stringify({
								...info,
								status: pass === '1' ? '同意' : '拒绝',
							}),
							businessId: props.location.query?.id,
							instanceId,
							pass,
							attachmentList: examineData?.url?.split(','),
							supplierList,
						}
						if (
							examineData?.sourceType === 0 ||
							examineData?.sourceType === 1
						) {
							flowParams.sourceType = examineData?.sourceType
						}
						contractAuditFlow(flowParams)
							.then((res: {msg: string; success: boolean}) => {
								if (res?.success) {
									if (pass === '3') {
										processRecordSave({
											bizType: 2,
											bizNo: props?.location?.query?.id,
											processId: instanceId,
										})
									}
									message.success(res.msg)
									goback()
								}
							})
							.catch((err: any) => {
								message.error(err)
							})
					} else {
						message.warning('请上传附件')
					}
				}
			}
		}
		return (
			<div className={styles.admittanceAdd}>
				<div className={`${styles.content} ${styles.formDetils}`}>
					{instanceId && (type === 'view' || type === 'process') ? (
						<Examine
							ref={examineRef}
							examineType={type === 'process'}
							orgId={props?.user?.orgId}
							activityId={activityId}
							processInstanceId={instanceId}
							required
							recommendData={recommendData}
							passStatus={passStatus}
							bizNo={props.location.query?.id}
						/>
					) : (
						''
					)}
					<Collapse
						defaultActiveKey={['1', '2', '3', '4', '5', '6']}
						ghost
						expandIconPosition="end">
						<Panel header={customizeHeader('基础信息')} key="1">
							<Form
								form={form}
								name="basic"
								layout="horizontal"
								labelCol={{flex: '120px'}}
								labelAlign="right"
								labelWrap
								initialValues={{remember: true}}
								autoComplete="off"
								disabled={
									type === 'view' || type === 'process'
								}>
								<Row gutter={12}>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="采购申请单号"
											name="requisitionNo"
											rules={[{required: true}]}>
											<Input
												placeholder="请输入"
												disabled
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="需求组织"
											name="requisitionOrgid"
											rules={[{required: true}]}>
											<TreeSelect
												showSearch
												treeNodeFilterProp="name"
												style={{width: '100%'}}
												placeholder="请选择"
												fieldNames={{
													label: 'name',
													value: 'id',
												}}
												treeDefaultExpandAll
												treeData={orgList}
												onChange={
													onRequisitionOrgChange
												}
												disabled={
													type === 'view' ||
													type === 'process'
												}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="城市"
											name="city"
											rules={[{required: true}]}>
											<Cascader
												fieldNames={{
													label: 'name',
													value: 'id',
													children: 'cityInfoList',
												}}
												options={citysList}
												placeholder="请选择"
												onChange={onCitysChange}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										{type === 'view' ? (
											<Form.Item
												label="需求部门"
												name="requisitionDeptname"
												rules={[{required: true}]}>
												<Input placeholder="请选择" />
											</Form.Item>
										) : (
											<Form.Item
												label="需求部门"
												name="requisitionDeptid"
												rules={[{required: true}]}>
												<TreeSelect
													showSearch
													treeNodeFilterProp="name"
													style={{width: '100%'}}
													placeholder="请选择"
													fieldNames={{
														label: 'name',
														value: 'id',
													}}
													treeDefaultExpandAll
													treeData={deptList}
													onChange={onApplyDeptChange}
												/>
											</Form.Item>
										)}
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="采购类目"
											name="requisitionType"
											rules={[{required: true}]}>
											<TreeSelect
												showSearch
												treeNodeFilterProp="dictValue"
												placeholder="请选择"
												style={{width: '100%'}}
												fieldNames={{
													value: 'key',
													children: 'childList',
													label: 'value',
												}}
												treeData={requisitionTypeList}
												onChange={
													onRequisitionTypeChange
												}
												disabled={
													type === 'view' ||
													type === 'process'
												}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="采购预估金额"
											name="estimatedAmount"
											getValueFromEvent={
												(event: any) =>
													event.target.value.replace(
														/^(-)*(\d+)\.(\d\d).*$/,
														'$1$2.$3',
													) // 只能输入两位小数
											}
											rules={[
												{
													required: true,
													pattern: twoDecimalPattern,
													message:
														'请输入正确的采购预估金额',
												},
											]}>
											{type === 'view' ||
											type === 'process' ? (
												<>
													<span>
														{estimatedAmount}元
													</span>
												</>
											) : (
												<Input
													placeholder="请输入"
													suffix="元"
												/>
											)}
										</Form.Item>
									</Col>
									<Col sm={{span: 24}} />
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="采购描述"
											name="requisitionDesc"
											rules={[
												{
													required: true,
												},
											]}>
											<TextArea
												maxLength={200}
												placeholder="请输入（最多200个字）"
												autoSize={{
													minRows: 3,
													maxRows: 6,
												}}
											/>
										</Form.Item>
									</Col>
									<Col sm={{span: 24}} />
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="申请人"
											name="applicantName">
											<Input
												placeholder="请输入"
												disabled
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="申请时间"
											name="applyTime">
											{processOpen === 1 ? (
												<DatePicker
													format="YYYY-MM-DD HH:mm:ss"
													disabled
												/>
											) : (
												<DatePicker
													format="YYYY-MM-DD"
													allowClear={false}
													disabled={
														type === 'view' ||
														type === 'process'
													}
												/>
											)}
										</Form.Item>
									</Col>
									<Col sm={{span: 24}} />
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="附件上传"
											name="attachmentList">
											<Upload
												{...uploadMoreProps(
													'purchase',
													0,
													fileList,
													(
														t: string,
														flist: any,
														file: any,
													) => {
														if (t === 'sizeBig') {
															const list =
																flist?.filter(
																	(
																		item: any,
																	) =>
																		item.id !==
																		file.id,
																)
															setFileList(
																() => list,
															)
															return false
														}
														if (t === 'error') {
															const list =
																flist?.filter(
																	(
																		item: any,
																	) =>
																		item.id !==
																		file.id,
																)
															setFileList(
																() => list,
															)
														} else if (
															[
																'done',
																'setData',
															].includes(t)
														) {
															setFileList(
																() => flist,
															)
														} else if (
															t === 'remove'
														) {
															const list =
																flist?.filter(
																	(
																		item: any,
																	) =>
																		item.id !==
																		file.id,
																)
															setFileList(
																() => list,
															)
														}
														return true
													},
												)}>
												<Button
													type="primary"
													ghost
													shape="round"
													size="small">
													请选择文件
												</Button>
											</Upload>
										</Form.Item>
									</Col>
									<Col sm={{span: 24}}>
										<div className="uploadTip">
											附件说明：附件最大支持200M，支持格式：PDF、Word、Excel、JPG、PNG、ZIP、RAR
										</div>
									</Col>
								</Row>
							</Form>
							{recommend === '1' &&
							(recommendData?.length ||
								(processOpen === 1 &&
									(type === 'add' || type === 'edit'))) ? (
								<RecommendList
									select
									type={type}
									recommendData={recommendData}
									setRecommendData={setRecommendData}
									recommendStatus={recommendStatus}
									setRecommendStatus={setRecommendStatus}
								/>
							) : (
								''
							)}
						</Panel>
						<Panel header={customizeHeader('立项信息')} key="2">
							<Form
								form={initiationForm}
								name="initiationForm"
								layout="horizontal"
								labelCol={{flex: '100px'}}
								labelAlign="right"
								labelWrap
								initialValues={{remember: true}}
								disabled={type === 'view' || type === 'process'}
								autoComplete="off">
								<Row gutter={12}>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="立项名称"
											name="projectName">
											<Input
												readOnly
												onClick={() => setIsOpen(true)}
												placeholder="请输入"
											/>
											{/* <Select
												showSearch
												allowClear
												placeholder="请选择"
												optionFilterProp="projectName"
												fieldNames={{
													label: 'projectName',
													value: 'id',
												}}
												onChange={onApplycostIdChange}
												options={initiationList}
											/> */}
										</Form.Item>
									</Col>
									{type !== 'view' && type !== 'process' ? (
										<Col
											sm={{span: 24}}
											md={{span: 12}}
											lg={{span: 8}}>
											<Space size={12}>
												<Button
													type="primary"
													onClick={() =>
														setIsOpen(true)
													}>
													选择
												</Button>
												<Button
													onClick={() => {
														setOtherParams({
															...otherParams,
															applycostId: 0,
															applycostName: '',
														})
														setCheckData([])
														setInitiationView([])
														initiationForm.setFieldsValue(
															{projectName: null},
														)
													}}>
													清空
												</Button>
											</Space>
										</Col>
									) : null}
									{/* <Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="立项名称"
											name="applycostId">
											<Search
												placeholder="input search text"
												onSearch={onSearch}
												style={{width: 200}}
											/>
										</Form.Item>
									</Col> */}
								</Row>
							</Form>
							<CustomTable
								params={{
									current: 1,
									size: 10,
								}}
								columns={initiationColumns}
								loading={false}
								dataSource={initiationView}
							/>
						</Panel>
						{((type === 'add' || type === 'edit') &&
							processOpen !== 1) ||
						(type === 'view' &&
							(auditStatusType === '1' ||
								auditStatusType === '9') &&
							(supplierView?.[0]?.contactPhone ||
								supplierView?.[0]?.supplierCode ||
								supplierView?.[0]?.supplierName)) ? (
							<Panel
								header={customizeHeader('供应商信息')}
								key="3">
								<Form
									form={supplierForm}
									name="basic"
									layout="horizontal"
									labelCol={{
										flex: recommendSupplier?.length
											? '150px'
											: '100px',
									}}
									labelAlign="right"
									labelWrap
									disabled={type === 'view'}
									autoComplete="off">
									{recommendSupplier?.length ? (
										<Row gutter={12}>
											<Col
												sm={{span: 24}}
												md={{span: 12}}
												lg={{span: 8}}>
												<Form.Item
													label="采购资源请求方式"
													name="sourceType">
													<Input
														placeholder="-"
														disabled
													/>
												</Form.Item>
											</Col>
											<Col sm={{span: 24}}>
												<RecommendList
													select={false}
													showName={false}
													type={type}
													recommendData={
														recommendSupplier
													}
													recommendStatus={1}
												/>
											</Col>
										</Row>
									) : (
										<Row gutter={12}>
											<Col
												sm={{span: 24}}
												md={{span: 12}}
												lg={{span: 8}}>
												<Form.Item
													label="供应商名称"
													name="supplierNo"
													rules={[
														{
															required: true,
														},
													]}>
													<Select
														showSearch
														placeholder="请选择"
														optionFilterProp="supplierName"
														fieldNames={{
															label: 'supplierName',
															value: 'supplierCode',
														}}
														options={supplierList}
														onChange={
															onAccessListChange
														}
													/>
												</Form.Item>
											</Col>
											<Col sm={{span: 24}}>
												<CustomTable
													columns={supplierColumns}
													loading={false}
													dataSource={supplierView}
												/>
											</Col>
										</Row>
									)}
								</Form>
							</Panel>
						) : (
							''
						)}
						{type !== 'add' && auditStatusType !== '3' ? (
							<>
								<Panel
									header={customizeHeader('采购合同')}
									key="4">
									<CustomTable
										scroll={{y: 480}}
										columns={contractColumns}
										loading={false}
										dataSource={contractView}
									/>
								</Panel>
								<Panel
									header={customizeHeader('采购计划')}
									key="5">
									<CustomTable
										scroll={{y: 480}}
										columns={planColumns}
										loading={false}
										dataSource={planView}
									/>
								</Panel>
							</>
						) : null}
						{type === 'view' ? (
							<Panel
								header={customizeHeader('操作记录')}
								key="6"
								forceRender>
								<OperationRecord
									businessId={props.location.query?.id}
									businessType={32}
								/>
							</Panel>
						) : (
							''
						)}
					</Collapse>
					<div className={styles.wrap}>
						<Button
							onClick={() => {
								goback()
							}}>
							取消
						</Button>
						{type !== 'view' && type !== 'process' ? (
							<>
								<Button
									type="primary"
									htmlType="submit"
									onClick={() => submit('save')}>
									保存
								</Button>
								<Button
									type="primary"
									htmlType="submit"
									onClick={() => submit('submit')}>
									提交
								</Button>
							</>
						) : null}
						{type === 'process' ? (
							<>
								<Button
									type="primary"
									htmlType="submit"
									onClick={() => {
										setPassStatus('1')
										setTimeout(() => {
											onCompleteTask('1')
										}, 100)
									}}>
									同意
								</Button>
								<Button
									onClick={() => {
										setPassStatus('3')
										setTimeout(() => {
											onCompleteTask('3')
										}, 100)
									}}>
									拒绝
								</Button>
							</>
						) : (
							''
						)}
					</div>
					<Modal
						title="立项信息选择"
						open={isOpen}
						onCancel={() => {
							setSeachFormData({})
							setIsOpen(false)
						}}
						width="50%"
						destroyOnClose
						footer={
							<>
								<Button
									size="small"
									onClick={() => {
										setSeachFormData({})
										setIsOpen(false)
									}}>
									取消
								</Button>
								<Button
									size="small"
									type="primary"
									onClick={() => onApplycostIdChange()}>
									确定
								</Button>
							</>
						}>
						<>
							<div
								className="formDataInit"
								style={{margin: '0 0 12px'}}>
								{formDataInit && (
									<SearchForm
										onFinish={onFinish}
										onReset={onReset}
										formItems={formDataInit}
										formLayout={formItemLayout}
									/>
								)}
							</div>
							<CustomTable
								params={params}
								scroll={{y: 350}}
								columns={initiationSelectColumns}
								loading={false}
								kid="id"
								showRowSelection
								type="radio"
								selectCallback={(
									keys: any,
									selectData: any,
								) => {
									setCheckData(selectData)
								}}
								pagination
								total={total}
								callback={(pagination: any) => {
									setParams(pagination)
								}}
								defaultSelectedRowKeys={
									checkData[0] ? [checkData[0]?.id] : []
								}
								dataSource={pageInitiationList}
							/>
						</>
					</Modal>
				</div>
			</div>
		)
	},
)
export default connect(({global, user}: any) => ({
	global,
	user,
}))(add)
